import { _decorator, Collider2D, Color, Component, Contact2DType, IPhysics2DContact, Node, PolygonCollider2D, Sprite, tween } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('GateCollisionController')
export class GateCollisionController extends Component {
    colliders: Collider2D[] = null;
    sprite: Sprite = null;
    // 当前接触的碰撞区域计数
    private contactCount: number = 0;
    onLoad() {
        this.colliders = this.node.getComponents(Collider2D);
        this.sprite = this.node.getComponent(Sprite);
    }
    start() {
        this.colliders.forEach(collider => {
            //判断碰撞体的tag是否为1，将该碰撞体作为判断遮挡传感器，对应碰撞体组件里tag记得改为1
            if (collider.tag == 1) {

                //判断获取的碰撞体传感器是多边形碰撞体，则继续
                if (collider instanceof PolygonCollider2D) {
                    if (!collider) return;
                    // 注册单个碰撞体的事件处理
                    collider.on(Contact2DType.BEGIN_CONTACT, this.activeTransparency, this);
                    collider.on(Contact2DType.END_CONTACT, this.endTransparency, this);
                }
            }
        })
    }

    activeTransparency(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if (otherCollider.node.name == 'Player1') {
            // 进入碰撞区域，接触计数+1
            this.contactCount++;
            // console.log("开始碰撞" + this.contactCount);

            if (this.contactCount === 1) {
                // this.sprite.color = new Color(255, 255, 255, 128);
                // 定义起始颜色和结束颜色
                const endColor = new Color(255, 255, 255, 65);
                // 使用 cc.tween 创建颜色过渡动画
                tween(this.sprite)
                    .to(0.2, { color: endColor })  // 在0.2秒内过渡到endColor
                    .start();
            }
        }
    }
    endTransparency(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if (otherCollider.node.name == 'Player1') {
            //将-1后的this.contactCount值和0中的最大值赋给this.contactCount
            //这样只有在角色节点完全离开多边形碰撞体区域时this.contactCount才为0
            this.contactCount = Math.max(0, this.contactCount - 1);
            // console.log("结束碰撞后" + this.contactCount);

            if (this.contactCount === 0) {
                // this.sprite.color = new Color(255, 255, 255, 255)
                const endColor = new Color(255, 255, 255, 255);
                // 使用 cc.tween 创建颜色过渡动画
                tween(this.sprite)
                    .to(0.2, { color: endColor })  // 在0.2秒内过渡到endColor
                    .start();
            }
        }
    }

    onDestroy() {
        this.colliders.forEach(collider => {
            if (collider.tag == 1) {
                collider.off(Contact2DType.BEGIN_CONTACT, this.activeTransparency, this);
                collider.off(Contact2DType.END_CONTACT, this.endTransparency, this);
            }
        })
    }
}


